<?php
/**
 * @package     Localization.php
 * @author      Jing Tang <tangjing3321@gmail.com>
 * @link        http://www.slimphp.net/
 * @version     2.0
 * @copyright   Copyright (c) http://www.slimphp.net
 * @date        2017年8月15日
 */

namespace MaterialLocalization\Repositories;

/**
 * 素材本地化
 * 
 * @author Jing Tang <tangjing3321@gmail.com>
 */
class Localization
{
   
    /**
     * 下载素材
     * 
     * @return boolean
     */
    public function download()
    {
        // 下载处理
        $closure = function ($row) {
            $baseDir = config('mxu.static_path');
            $row['downloadCount'] = 0;
            // 图片素材
            if ($row['material_info']) {
                foreach ($row['material_info'] as $key => $material) {
                    $url = $material['host'] . $material['dir'] . $material['filepath'] . $material['filename'];
                    if (@download($url, $baseDir)) {
                        $row['downloadCount'] = $row['downloadCount'] + 1;
                        logger()->info(var_export($url, 1));
                    }
                    // 下载失败，结束这条下载流程
                    else {
                        model('Task')->where('id', '=', $row['id'])->renew(['faild_num' => $row['faild_num'] + 1, 'status' => 1]);
                        goto end;
                    }
                }
            }
            // 音视频素材
            if ($row['url']) {
                if (! @download($row['url'], $baseDir)) {
                    model('Task')->where('id', '=', $row['id'])->renew(['status' => 1]);
                }
                else {
                    $row['downloadCount'] = $row['downloadCount'] + 1;
                    logger()->info(var_export($row['url'], 1));
                }
            }
            // 下载成功更新下载状态
            if (count($row['material_info']) <= $row['downloadCount']) {
                model('Task')->where('id', '=', $row['id'])->renew(['status' => 2]);
            }
            end:
            return $row;
        };
        // 查询未下载任务
        $result = model('Task')->where('status', '<>', 2)->limit(10, 0)->orderBy('id')->bind($closure)->rows();
        return true;
    }
    
    /**
     * 回调通知
     * 
     * @return boolean
     */
    public function notify()
    {
        $contentIds = [];
        if ($materials = model('Task')->where('status', '=', 2)->where('is_notify', '=', 0)->limit(10, 0)->orderBy('id')->rows()) {
            $contentIds = @array_column($materials, 'content_id');
            if ($contentIds) {
                $timestamp = time();
                $signature = hash_hmac('sha1', config('mxu.appid') . config('mxu.appkey') . $timestamp, $timestamp, false);
                $args = [
                    'rids' => implode(',', $contentIds),
                    'signature' => $signature,
                    'timestamp' => $timestamp,
                ];
                $curl = curl()->put(config('mxu.api.confirmPush'), $args);
                if (! $curl->error) {
                    logger()->info(var_export($curl->response, 1));
                    if ($data = @json_decode($curl->response, true)['data']) {
                        $successContentIds = [];
                        foreach ($data as $key => $value) {
                            if ($value) {
                                $successContentIds[] = $key;
                            }
                        }
                    }
                    if ($successContentIds) {
                        $result = model('Task')->whereIn('content_id', $successContentIds)->renew(['is_notify' => 1]);
                    }
                }
                else {
                    $url = config('mxu.api.confirmPush') . '?' . http_build_query($args);
                    logger()->info(var_export([$curl->error_code, $curl->error_message, $url], 1));
                    return false;
                }
            }
        }
        return true;
    }
    
    /**
     * 邮件错误报告
     * 
     * @param string $body
     * @return boolean
     */
    public function errorReportMail($body = '')
    {
        $config = config('mail');
        $time = time();
        if (($time - cache()->get('errorReportMail.sendTime', 0)) > $config['interval'] && $config['disable']) {
            $mail = new \Nette\Mail\Message();
            $mail->setFrom($config['from'])
            ->addTo($config['to'])
            ->setSubject($config['subject'])
            ->setBody($body);
            
            $mailer = new \Nette\Mail\SmtpMailer([
                'host' => $config['host'],
                'username' => $config['username'],
                'password' => $config['password']
            ]);
            $mailer->send($mail);
            cache()->forever('errorReportMail.sendTime', $time);
        }
        
        return true;
    }
}